package nl.hanze.FlitsNieuws.location;

import android.app.Activity;
import android.content.Context;
import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.SystemClock;
import java.util.List;

/**
 * Deze klasse handelt alle GPS zaken af, geeft de huidige geolocatie terug en ook een reverse
 * lookup van het adres op basis van de geolocatie. Tevens bevat het methoden om te controleren
 * of er GPS en een positie beschikbaar zijn.
 *
 * @author alex
 *
 */
public class LocationService extends Activity implements LocationListener {
    private final int GPS_FIX_TIME = 15000;
    private LocationManager locManager;
    private String locationProvider;
    private Location location;
    private Context context;
    private Long lastFixTime;

    public LocationService(Context context) {
        this.context = context;
        locManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        Criteria criteria = new Criteria();
        criteria.setAccuracy(Criteria.ACCURACY_FINE);
        locationProvider = locManager.getBestProvider(criteria, false);
        location = locManager.getLastKnownLocation(locationProvider);
    }

    public boolean isGpsEnabled() {
        return locManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
    }

    public boolean isGpsFixAvailable(){
        return location != null && ((SystemClock.elapsedRealtime() - lastFixTime) < GPS_FIX_TIME);    
    }    
    
    public boolean isPositionAvailable() {
        return location != null;
    }

    public Location getLocation() {
        return location;
    }

    public Address getAddress() {
        Address address = null;
        Geocoder geocoder = new Geocoder(context);
        try {
            List<Address> adresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);

            if (adresses.size() > 0) {
                address = adresses.get(0);
            }
        } catch (Exception e) {
        }
        return address;
    }

    public void getUpdates() {
        locManager.requestLocationUpdates(locationProvider, 400, 1, this);
    }

    public void stopUpdates() {
        locManager.removeUpdates(this);
    }

    public void onLocationChanged(Location location) {
        lastFixTime = SystemClock.elapsedRealtime();
        this.location = location;
    }

    public void onProviderDisabled(String provider) {
        // TODO Auto-generated method stub		
    }

    public void onProviderEnabled(String provider) {
        // TODO Auto-generated method stub		
    }

    public void onStatusChanged(String provider, int status, Bundle extras) {
        // TODO Auto-generated method stub		
    }
}
